<template>
  <div class="app-container">

    <!-- 过滤器 -->
    <div class="filter-container">
      <span>姓名: </span>
      <el-input
        v-model="listQuery.name"
        placeholder="请输入姓名"
        style="width: 200px;"
        class="filter-item"
      />
      <!-- 空隙 -->
      <div style="width: 20px; display: inline-block;" />
      <span>住院号: </span>
      <el-input
        v-model="listQuery.admission_no"
        placeholder="请输入住院号"
        style="width: 200px;"
        class="filter-item"
      />
      <!-- 空隙 -->
      <div style="width: 20px; display: inline-block;" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <!--隐藏
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-download" @click="exportExcel">
        导出
      </el-button>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-plus" @click="openAddDialog">
        新增
      </el-button>
      -->
    </div>

    <!-- 表格 -->
    <el-table v-loading="listLoading" :data="userinfo" border fit highlight-current-row style="width: 100%">
      <!-- ID -->
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <!-- 姓名 -->
      <el-table-column align="center" label="姓名" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <!-- 住院号 -->
      <el-table-column align="center" label="住院号" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.admission_no }}</span>
        </template>
      </el-table-column>
      <!-- 电话 -->
      <el-table-column align="center" label="电话" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>
      <!-- 删除操作列 -->
      <el-table-column align="center" label="操作" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleClick(scope.row.id)">
            查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 新增对话框 -->
    <el-dialog title="新增患者" :visible.sync="addDialogVisible">
      <el-form :model="addForm" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="住院号">
          <el-input v-model="addForm.admission_no" />
        </el-form-item>
        <el-form-item label="身份证号码">
          <el-input v-model="addForm.identity_card" />
        </el-form-item>
        <el-form-item label="诊断">
          <el-input v-model="addForm.diagnosis" />
        </el-form-item>
        <el-form-item label="合并疾病">
          <el-input v-model="addForm.comorbidity" />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="addForm.age" />
        </el-form-item>
        <el-form-item label="治疗方式">
          <el-input v-model="addForm.therapeutic_modality" />
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="addForm.gender" />
        </el-form-item>
        <el-form-item label="生育史">
          <el-input v-model="addForm.fertility_history" />
        </el-form-item>
        <el-form-item label="入院日期">
          <el-date-picker
            v-model="addForm.inhospital_time"
            type="datetime"
            placeholder="请选择入院日期和时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="入院时体温">
          <el-input v-model="addForm.temperature" />
        </el-form-item>
        <el-form-item label="入院时脉搏">
          <el-input v-model="addForm.pulse" />
        </el-form-item>
        <el-form-item label="入院时呼吸">
          <el-input v-model="addForm.respiration_rate" />
        </el-form-item>
        <el-form-item label="入院时血压">
          <el-input v-model="addForm.blood_pressure" />
        </el-form-item>
        <el-form-item label="出院日期">
          <el-date-picker
            v-model="addForm.outhospital_time"
            type="datetime"
            placeholder="请选择出院日期和时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="出院时体温">
          <el-input v-model="addForm.temperature_out" />
        </el-form-item>
        <el-form-item label="出院时脉搏">
          <el-input v-model="addForm.pulse_out" />
        </el-form-item>
        <el-form-item label="出院时呼吸">
          <el-input v-model="addForm.respiration_rate_out" />
        </el-form-item>
        <el-form-item label="出院时血压">
          <el-input v-model="addForm.blood_pressure_out" />
        </el-form-item>
        <el-form-item label="2个月时体温">
          <el-input v-model="addForm.temperature_2_months" />
        </el-form-item>
        <el-form-item label="2个月时脉搏">
          <el-input v-model="addForm.pulse_2_months" />
        </el-form-item>
        <el-form-item label="2个月时呼吸">
          <el-input v-model="addForm.respiration_rate_2_months" />
        </el-form-item>
        <el-form-item label="2个月时血压">
          <el-input v-model="addForm.blood_pressure_2_months" />
        </el-form-item>
        <el-form-item label="婚姻状况">
          <el-input v-model="addForm.marital_status" />
        </el-form-item>
        <el-form-item label="受教育程度">
          <el-input v-model="addForm.education_level" />
        </el-form-item>
        <el-form-item label="职业">
          <el-input v-model="addForm.occupation" />
        </el-form-item>
        <el-form-item label="医疗费用承担方式">
          <el-input v-model="addForm.methods_of_medical_cost_coverage" />
        </el-form-item>
        <el-form-item label="居住地">
          <el-input v-model="addForm.address" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="addForm.phone" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="addForm.notes" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="addForm.roles" placeholder="请选择角色" style="width: 100%;">
            <el-option label="User" value="user" />
            <el-option label="Doctor" value="doctor" />
          </el-select>
        </el-form-item>
        <el-form-item label="group_class">
          <el-input v-model="addForm.group_class" :disabled="true" />
        </el-form-item>
      </el-form>
      <!-- 对话框底部的按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAdd">保存</el-button>
      </div>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog title="编辑患者" :visible.sync="editDialogVisible">
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="姓名">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="住院号">
          <el-input v-model="editForm.admission_no" />
        </el-form-item>
        <el-form-item label="身份证号码">
          <el-input v-model="editForm.identity_card" />
        </el-form-item>
        <el-form-item label="诊断">
          <el-input v-model="editForm.diagnosis" />
        </el-form-item>
        <el-form-item label="合并疾病">
          <el-input v-model="editForm.comorbidity" />
        </el-form-item>
        <el-form-item label="年龄">
          <el-input v-model="editForm.age" />
        </el-form-item>
        <el-form-item label="治疗方式">
          <el-input v-model="editForm.therapeutic_modality" />
        </el-form-item>
        <el-form-item label="性别">
          <el-input v-model="editForm.gender" />
        </el-form-item>
        <el-form-item label="生育史">
          <el-input v-model="editForm.fertility_history" />
        </el-form-item>
        <el-form-item label="入院日期">
          <el-date-picker
            v-model="editForm.inhospital_time"
            type="datetime"
            placeholder="请选择入院日期和时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="入院时体温">
          <el-input v-model="editForm.temperature" />
        </el-form-item>
        <el-form-item label="入院时脉搏">
          <el-input v-model="editForm.pulse" />
        </el-form-item>
        <el-form-item label="入院时呼吸">
          <el-input v-model="editForm.respiration_rate" />
        </el-form-item>
        <el-form-item label="入院时血压">
          <el-input v-model="editForm.blood_pressure" />
        </el-form-item>
        <el-form-item label="出院日期">
          <el-date-picker
            v-model="editForm.outhospital_time"
            type="datetime"
            placeholder="请选择出院日期和时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="出院时体温">
          <el-input v-model="editForm.temperature_out" />
        </el-form-item>
        <el-form-item label="出院时脉搏">
          <el-input v-model="editForm.pulse_out" />
        </el-form-item>
        <el-form-item label="出院时呼吸">
          <el-input v-model="editForm.respiration_rate_out" />
        </el-form-item>
        <el-form-item label="出院时血压">
          <el-input v-model="editForm.blood_pressure_out" />
        </el-form-item>
        <el-form-item label="2个月时体温">
          <el-input v-model="editForm.temperature_2_months" />
        </el-form-item>
        <el-form-item label="2个月时脉搏">
          <el-input v-model="editForm.pulse_2_months" />
        </el-form-item>
        <el-form-item label="2个月时呼吸">
          <el-input v-model="editForm.respiration_rate_2_months" />
        </el-form-item>
        <el-form-item label="2个月时血压">
          <el-input v-model="editForm.blood_pressure_2_months" />
        </el-form-item>
        <el-form-item label="婚姻状况">
          <el-input v-model="editForm.marital_status" />
        </el-form-item>
        <el-form-item label="受教育程度">
          <el-input v-model="editForm.education_level" />
        </el-form-item>
        <el-form-item label="职业">
          <el-input v-model="editForm.occupation" />
        </el-form-item>
        <el-form-item label="医疗费用承担方式">
          <el-input v-model="editForm.methods_of_medical_cost_coverage" />
        </el-form-item>
        <el-form-item label="居住地">
          <el-input v-model="editForm.address" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.notes" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editForm.roles" placeholder="请选择角色" style="width: 100%;">
            <el-option label="User" value="user" />
            <el-option label="Doctor" value="doctor" />
          </el-select>
        </el-form-item>
        <el-form-item label="group_class">
          <el-input v-model="addForm.group_class" :disabled="true" />
        </el-form-item>
      </el-form>
      <!-- 对话框底部的按钮 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleEdit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { patientList } from '@/api/nurse/patient_list' // 导入查询接口
import Pagination from '@/components/Pagination'
import { deletePatient } from '@/api/nurse/patient_list' // 导入删除接口
import { addPatient } from '@/api/nurse/patient_list' // 导入新增接口
import { updatePatient } from '@/api/nurse/patient_list' // 导入编辑接口
import * as XLSX from 'xlsx'

export default {
  name: 'PatientList',
  components: { Pagination },
  data() {
    return {
      userinfo: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: '', // 添加姓名搜索
        admission_no: '', // 添加住院号搜索
        group_class: '1' // 添加 group_class 过滤，默认值为 1 ai组
      },
      addDialogVisible: false, // 控制新增对话框的显示
      addForm: { // 新增表单
        name: '',
        admission_no: '',
        identity_card: '',
        diagnosis: '',
        comorbidity: '',
        age: '',
        therapeutic_modality: '',
        gender: '',
        fertility_history: '',
        inhospital_time: new Date().toISOString(),
        temperature: '',
        pulse: '',
        respiration_rate: '',
        blood_pressure: '',
        outhospital_time: new Date().toISOString(),
        temperature_out: '',
        pulse_out: '',
        respiration_rate_out: '',
        blood_pressure_out: '',
        temperature_2_months: '',
        pulse_2_months: '',
        respiration_rate_2_months: '',
        blood_pressure_2_months: '',
        marital_status: '',
        education_level: '',
        occupation: '',
        methods_of_medical_cost_coverage: '',
        address: '',
        phone: '',
        notes: '',
        create_time: new Date().toISOString(),
        update_time: new Date().toISOString(),
        roles: '',
        group_class: ''
      },
      addForm: {
        // 新增页面字段初始化默认值为1
        group_class: '1'
        // 其他字段
      },
      idd: { 'id': 1 },
      editDialogVisible: false, // 控制编辑对话框的显示
      editForm: { // 编辑表单
        id: '',
        name: '',
        admission_no: '',
        identity_card: '',
        diagnosis: '',
        comorbidity: '',
        age: '',
        therapeutic_modality: '',
        gender: '',
        fertility_history: '',
        inhospital_time: new Date().toISOString(),
        temperature: '',
        pulse: '',
        respiration_rate: '',
        blood_pressure: '',
        outhospital_time: new Date().toISOString(),
        temperature_out: '',
        pulse_out: '',
        respiration_rate_out: '',
        blood_pressure_out: '',
        temperature_2_months: '',
        pulse_2_months: '',
        respiration_rate_2_months: '',
        blood_pressure_2_months: '',
        marital_status: '',
        education_level: '',
        occupation: '',
        methods_of_medical_cost_coverage: '',
        address: '',
        phone: '',
        notes: '',
        create_time: new Date().toISOString(),
        update_time: new Date().toISOString(),
        roles: '',
        group_class: ''
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      patientList(this.listQuery).then(response => {
        // 过滤数据，新增 group 条件
        const filteredData = response.data.userinfo.filter(item => {
          const admissionNoMatch = this.listQuery.admission_no === '' || item[2].includes(this.listQuery.admission_no)
          const nameMatch = this.listQuery.name === '' || item[1].includes(this.listQuery.name)
          const groupMatch = item[35] === this.listQuery.group_class // 过滤 group 等于 1 的数据
          return admissionNoMatch && nameMatch && groupMatch
        })

        // 确定当前页面的数据起始和结束索引
        const start = (this.listQuery.page - 1) * this.listQuery.limit
        const end = start + this.listQuery.limit

        // 使用 slice 截取当前页的数据
        const paginatedData = filteredData.slice(start, end)

        // 查看数据
        // 遍历 `paginatedData` 数组，构建每一行的数据
        this.userinfo = paginatedData.map(item => ({
          id: item[0],
          name: item[1],
          admission_no: item[2],
          identity_card: item[3],
          diagnosis: item[4],
          comorbidity: item[5],
          age: item[6],
          therapeutic_modality: item[7],
          gender: item[8],
          fertility_history: item[9],
          inhospital_time: item[10],
          temperature: item[11],
          pulse: item[12],
          respiration_rate: item[13],
          blood_pressure: item[14],
          outhospital_time: item[15],
          temperature_out: item[16],
          pulse_out: item[17],
          respiration_rate_out: item[18],
          blood_pressure_out: item[19],
          temperature_2_months: item[20],
          pulse_2_months: item[21],
          respiration_rate_2_months: item[22],
          blood_pressure_2_months: item[23],
          marital_status: item[24],
          education_level: item[25],
          occupation: item[26],
          methods_of_medical_cost_coverage: item[27],
          address: item[28],
          phone: item[29],
          notes: item[30],
          create_time: item[31],
          update_time: item[32],
          roles: item[34],
          group_class: item[35]
        }))

        // 设置 total 的值为过滤后的数据总数
        this.total = filteredData.length
        this.listLoading = false
      }).catch(error => {
        console.error('Failed to fetch data:', error)
        this.listLoading = false
      })
    },
    // 删除逻辑
    handleDelete(id) {
      console.log(id)
      this.$confirm('确定删除此条记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        const iddd = { 'id': id }
        console.log(iddd)
        deletePatient(iddd)
          .then(response => {
            this.$message.success('删除成功!')
            this.getList() // 删除成功后刷新列表
          })
          .catch(error => {
            console.error('Failed to delete data:', error)
            this.$message.error('删除失败!')
          })
          .finally(() => {
            this.listLoading = false
          })
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 打开新增对话框
    openAddDialog() {
      console.log('新增按钮被点击了') // 检查点击事件
      this.addDialogVisible = true
    },
    // 保存新增数据
    handleAdd() {
      // 检查表单是否有效，并将时间字段转换为 'YYYY-MM-DD HH:mm:ss' 格式
      const formatDate = (date) => {
        const d = new Date(date)
        const year = d.getFullYear()
        const month = (d.getMonth() + 1).toString().padStart(2, '0')
        const day = d.getDate().toString().padStart(2, '0')
        const hours = d.getHours().toString().padStart(2, '0')
        const minutes = d.getMinutes().toString().padStart(2, '0')
        const seconds = d.getSeconds().toString().padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }

      // 处理入院和出院日期字段，并将格式化后的日期赋值回 addForm
      this.addForm.inhospital_time = formatDate(this.addForm.inhospital_time)
      this.addForm.outhospital_time = formatDate(this.addForm.outhospital_time)

      // 打印新增的数据
      console.log('新增数据', this.addForm)

      // 发送新增请求
      addPatient(this.addForm).then(() => {
        this.$message.success('新增成功!')
        this.addDialogVisible = false // 关闭对话框
        this.getList() // 刷新列表
      }).catch(() => {
        this.$message.error('新增失败!')
      })
    },
    // 打开编辑对话框
    openEditDialog(row) {
      // 将选中行的数据填充到 editForm 中
      this.editForm = { ...row }
      this.editDialogVisible = true
    },
    // 更新患者信息
    handleEdit() {
      // 将表单中的时间字段转换为 'YYYY-MM-DD HH:mm:ss' 格式
      const formatDate = (date) => {
        const d = new Date(date)
        const year = d.getFullYear()
        const month = (d.getMonth() + 1).toString().padStart(2, '0')
        const day = d.getDate().toString().padStart(2, '0')
        const hours = d.getHours().toString().padStart(2, '0')
        const minutes = d.getMinutes().toString().padStart(2, '0')
        const seconds = d.getSeconds().toString().padStart(2, '0')
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
      }

      // 处理入院和出院日期字段，并将格式化后的日期赋值回 editForm
      this.editForm.inhospital_time = formatDate(this.editForm.inhospital_time)
      this.editForm.outhospital_time = formatDate(this.editForm.outhospital_time)

      // 打印更新的数据
      console.log('更新数据', this.editForm)

      // 发送更新请求
      updatePatient(this.editForm).then(() => {
        this.$message.success('更新成功!')
        this.editDialogVisible = false // 关闭对话框
        this.getList() // 刷新列表
      }).catch(() => {
        this.$message.error('更新失败!')
      })
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      return `${year}/${month}/${day}`
    },
    handleClick(id) {
      this.$router.push({
        path: '/zhjkaixinli/hzxilbdb',
        query: { id: id }
      })
    },
    // 导出 Excel
    exportExcel() {
      // 临时保存当前的分页限制和页码
      const oldLimit = this.listQuery.limit
      const oldPage = this.listQuery.page

      // 设置 limit 为一个足够大的值，确保获取到所有数据
      this.listQuery.limit = Infinity
      this.listQuery.page = 1

      // 获取所有数据
      patientList(this.listQuery).then(response => {
        // 重置分页限制和页码
        this.listQuery.limit = oldLimit
        this.listQuery.page = oldPage

        // 过滤数据
        const filteredData = response.data.userinfo.filter(item => {
          const admissionNoMatch = this.listQuery.admission_no === '' || item[2].includes(this.listQuery.admission_no)
          const nameMatch = this.listQuery.name === '' || item[1].includes(this.listQuery.name)
          const groupMatch = item[35] === this.listQuery.group_class // 过滤 group 等于 1 的数据
          return admissionNoMatch && nameMatch && groupMatch
        })

        // 将所有数据格式化为 Excel 数据
        const exportData = filteredData.map(item => ({
          'ID': item[0],
          '姓名': item[1],
          '住院号': item[2],
          '身份证号码及账号': item[3],
          '诊断': item[4],
          '合并疾病': item[5],
          '年龄': item[6],
          '治疗方式': item[7],
          '性别': item[8],
          '生育史': item[9],
          '入院日期': this.formatDate(item[10]),
          '入院时体温': item[11],
          '入院时脉搏': item[12],
          '入院时呼吸': item[13],
          '入院时血压': item[14],
          '出院日期': this.formatDate(item[15]),
          '出院时体温': item[16],
          '出院时脉搏': item[17],
          '出院时呼吸': item[18],
          '出院时血压': item[19],
          '2个月时体温': item[20],
          '2个月时脉搏': item[21],
          '2个月时呼吸': item[22],
          '2个月时血压': item[23],
          '婚姻状况': item[24],
          '教育程度': item[25],
          '职业': item[26],
          '医疗费用承担方式': item[27],
          '居住地': item[28],
          '电话': item[29],
          '备注': item[30],
          '创建时间': this.formatDate(item[31]),
          '更新时间': this.formatDate(item[32]),
          '角色': item[34],
          '组': item[35]
        }))

        // 创建工作簿和工作表
        const worksheet = XLSX.utils.json_to_sheet(exportData)
        const workbook = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(workbook, worksheet, '患者信息-ai组')

        // 导出 Excel 文件
        XLSX.writeFile(workbook, '患者信息-ai组.xlsx')
      }).catch(error => {
        console.error('Failed to fetch data:', error)
      })
    },

    // 格式化日期
    formatDate(date) {
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
    }
  }
}
</script>
